//
//  YYFacePlusPlus.m
//  FacePlusPlus
//
//  Created by luowei on 2018/10/22.
//  Copyright © 2018年 luowei. All rights reserved.
//

#import "YYFacePlusPlus.h"
#import "NSDictionaryUtils.h"
#import "MGFaceIDNetwork.h"
#import <MGFaceIDLiveDetect/MGFaceIDLiveDetect.h>

@interface YYFacePlusPlus ()
{
    NSInteger _cbId;
}
@property (nonatomic, strong) NSString *bizToken;
@end
@implementation YYFacePlusPlus

- (id)initWithUZWebView:(UZWebView *)webView_ { 
    if (self = [super initWithUZWebView:webView_]) {
        
    }
    return self;
}

- (void)dispose {
    //do clean
}


#pragma mark - js methods
- (void)authentication:(NSDictionary *)param {
    _cbId = [param integerValueForKey:@"cbId" defaultValue:0];
    NSString *cardName = [param stringValueForKey:@"cardName" defaultValue:nil];
    NSString *cardNumber = [param stringValueForKey:@"cardNumber" defaultValue:nil];
    if (!cardName || cardName.length == 0) {
        [self showtoast:@"认证人姓名不能为空" withData:nil withStatus:FALSE];
        return;
    }
    if (!cardNumber || cardNumber.length == 0) {
        [self showtoast:@"认证人身份证号不能为空" withData:nil withStatus:FALSE];
        return;
    }
    NSDictionary *feature = [self getFeatureByName:@"facePlusPlus"];
    NSString *apiKey = [feature stringValueForKey:@"apiKey" defaultValue:nil]; 
    NSString *apiSecret = [feature stringValueForKey:@"apiSecret" defaultValue:nil];
    [self getBizToken:cardName withIDCard:cardNumber apiKey:apiKey secret:apiSecret];
    
}

- (void)getBizToken:(NSString*)carName withIDCard:(NSString*)cardNumber apiKey:(NSString*)apiKey secret:(NSString*)apiSecret{
    NSMutableDictionary* liveInfoDict = [[NSMutableDictionary alloc] initWithCapacity:1];
    [liveInfoDict setObject:@"3" forKey:@"liveness_retry_count"];
    [liveInfoDict setObject:@"1" forKey:@"verbose"];
    [liveInfoDict setObject:@"2" forKey:@"security_level"];
    [liveInfoDict setObject:@"meglive" forKey:@"liveness_type"];
    
    __weak typeof(self) weakSelf = self;
    [[MGFaceIDNetwork singleton] queryMGFaceIDAntiSpoofingBizTokenWithUUID:[NSUUID UUID].UUIDString
                                                                          imageRef:nil
                                                                        liveConfig:liveInfoDict
                                                                           success:^(NSInteger statusCode, NSDictionary *responseObject) {
                                                                               if (statusCode == 200 && responseObject && [[responseObject allKeys] containsObject:@"biz_token"] && [responseObject objectForKey:@"biz_token"]) {
                                                                                   NSString *bizTokenStr = [responseObject objectForKey:@"biz_token"];
                                                                                   weakSelf.bizToken = bizTokenStr;
                                                                                   [weakSelf startFaceIDLiveDetect];
                                                                                   NSLog(@"%@",bizTokenStr);
                                                                               } else {
                                                                                   NSLog(@"获取 BizToken 失败");
                                                                                   [self showtoast:@"获取 BizToken 失败" withData:nil withStatus:FALSE];
                                                                               }
                                                                           } failure:^(NSInteger statusCode, NSError *error) {
                                                                               NSLog(@"%@",error);
                                                                               dispatch_async(dispatch_get_main_queue(), ^{
                                                                                   [self showtoast:@"清先获取 BizToken" withData:nil withStatus:FALSE];
                                                                               });
                                                                           }
                                                                            withIDCardName:carName
                                                                          withIDCardNumber:cardNumber
                                                                        apiKey:apiKey apiSecret:apiSecret];
}



- (void)startFaceIDLiveDetect {
    if (self.bizToken) {
        MGFaceIDLiveDetectError* error;
        MGFaceIDLiveDetectManager* liveDetectManager = [[MGFaceIDLiveDetectManager alloc] initMGFaceIDLiveDetectManagerWithBizToken:self.bizToken
                                                                                                                          extraData:@{} error:&error];
        if (error || !liveDetectManager) {
            [self showtoast:@"初始化失败" withData:nil withStatus:FALSE];
            return;
        }
        [liveDetectManager startMGFaceIDLiveDetectWithCurrentController:self.viewController
                                                               callback:^(MGFaceIDLiveDetectError *error, NSData *deltaData, NSString *bizTokenStr, NSDictionary *extraOutDataDict) {
                                                                   if (deltaData) {
                                                                       NSString *str  = [[NSString alloc] initWithData:deltaData encoding:NSUTF8StringEncoding];
                                                                       [self showtoast:@"验证成功" withData:str withStatus:TRUE];
                                                                   }else{
                                                                       [self showtoast:@"验证失败" withData:nil withStatus:FALSE];
                                                                   }
                                                               }];
    } else {
        [self showtoast:@"清先获取 BizToken" withData:nil withStatus:FALSE];
    }
}

- (void)showtoast:(NSString*)msg withData:(NSString*)data withStatus:(BOOL)success{
    if (_cbId > 0) {
        NSDictionary *ret = @{@"data":data,@"msg":msg,@"success":@(success)};
        [self sendResultEventWithCallbackId:_cbId dataDict:ret errDict:nil doDelete:YES];
    }
}
@end
